package com.unicom.office;

import com.unicom.office.config.OfficeConfig;
import com.unicom.office.func.FuncBase;
import com.unicom.office.runtime.OfficeRuntime;
import com.unicom.office.parser.OfficeParser;
import com.unicom.office.unit.OfficeUnit;
import com.unicom.office.util.FileUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OfficeMatchHelper {
    private OfficeParser officeParser;
    private OfficeRuntime officeRuntime;
    private FuncBase template;
    private OfficeConfig officeConfig;

    public OfficeMatchHelper(String templatePath, OfficeConfig config, OfficeRuntime runtime){
        this.officeConfig = config;
        officeRuntime = runtime;

        String ext = FileUtil.getExtension(templatePath);
        officeParser = OfficeHelper.getDefaultParser(ext);
        officeParser.setConfig(officeConfig);
        officeParser.setRuntime(runtime);
        template = officeParser.parse(templatePath);
    }

    public Map<String, Object> match(String dataPath){
        FuncBase parsed = officeParser.parse(dataPath);

        officeRuntime.in(new HashMap<String, Object>(), officeConfig);
        Object rendered = parsed.run(officeRuntime);
        if(rendered instanceof OfficeUnit){
            template.runForMatch((OfficeUnit) rendered, officeRuntime);
        }else if(rendered instanceof List && ((List<OfficeUnit>)rendered).size() > 0){
            template.runForMatch(((List<OfficeUnit>)rendered).get(0), officeRuntime);
        }
        return officeRuntime.getData();
    }
}
